<template>
  <ModelGround v-if="$store.state.pk.status === 'model'"></ModelGround>
  <MatchGround
    v-if="
      $store.state.pk.status === 'matching' || $store.state.pk.status === 'start-matching'
    "></MatchGround>
  <PlayGround v-if="$store.state.pk.status === 'playing'"> </PlayGround>
  <ResultBoard v-if="$store.state.pk.loser != 'none'"></ResultBoard>
</template>

<script>
import ModelGround from "@/components/ModelGround.vue";
import PlayGround from "@/components/PlayGround.vue";
import MatchGround from "@/components/MatchGround.vue";
import ResultBoard from "@/components/ResultBoard.vue";

import { onMounted, onUnmounted } from "vue";
import { useStore } from "vuex";

export default {
  components: {
    ModelGround,
    PlayGround,
    MatchGround,
    ResultBoard,
  },
  setup() {
    const store = useStore();
    const socketUrl = `ws://127.0.0.1:3000/websocket/${store.state.user.token}/`;

    store.commit("updateLoser", "none");
    store.commit("updateIsRecord", false);

    let socket = null;
    onMounted(() => {
      // 更新pk状态
      store.commit("updateStatus", "model");

      store.commit("updateOpponent", {
        username: "我的对手",
        photo:
          "https://king-of-bots.oss-cn-beijing.aliyuncs.com/image/%E6%88%91%E7%9A%84%E5%AF%B9%E6%89%8B%E5%A4%B4%E5%83%8F.png",
      });
      socket = new WebSocket(socketUrl);

      socket.onopen = () => {
        console.log("connected!");
        store.commit("updateSocket", socket);
      };

      socket.onmessage = (msg) => {
        const data = JSON.parse(msg.data);
        console.log("msg ========================" + msg.data);
        /**
         * msg ========================
         * {
         * "game":
         *    {
         *     "a_id":20,
         *     "b_id":21,
         *     "a_sy":1,
         *     "map":[[1,1,1,1,1,1,1,1,1,1,1,1,1,1],[1,0,0,0,0,1,0,0,0,0,0,0,0,1],[1,1,0,0,1,0,1,0,0,1,1,0,0,1],[1,0,0,0,0,1,0,0,0,0,0,0,0,1],[1,0,0,0,0,0,0,0,0,0,0,0,0,1],[1,0,0,1,0,0,1,0,0,0,1,0,0,1],[1,0,0,0,0,0,0,0,0,0,0,0,0,1],[1,0,0,1,0,0,0,1,0,0,1,0,0,1],[1,0,0,0,0,0,0,0,0,0,0,0,0,1],[1,0,0,0,0,0,0,0,1,0,0,0,0,1],[1,0,0,1,1,0,0,1,0,1,0,0,1,1],[1,0,0,0,0,0,0,0,1,0,0,0,0,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1]],"a_sx":11,"b_sy":12,"b_sx":1
         *     },
         * "opponent_username":"test1",
         * "opponent_photo":"https://cdn.acwing.com/media/user/profile/photo/55289_lg_5de0e068ab.webp",
         * "event":"start-matching"
         * }
         */

        if (data.event === "start-matching") {
          // 匹配成功
          store.commit("updateOpponent", {
            username: data.opponent_username,
            photo: data.opponent_photo,
          });

          // 判断用户是蓝色方还是红色方
          if (data.game.a_id == store.state.user.id) {
            store.commit("updateRedOrBlue", 0);
          } else {
            store.commit("updateRedOrBlue", 1);
          }

          store.commit("updateBeforeStart", "before-playing");
          setTimeout(() => {
            store.commit("updateStatus", "playing");
          }, 200);
          store.commit("updateGame", data.game);
        } else if (data.event === "move") {
          console.log(data);
          const game = store.state.pk.gameObject;
          const [snake0, snake1] = game.snakes;
          snake0.set_direction(data.a_direction);
          snake1.set_direction(data.b_direction);
        } else if (data.event === "result") {
          console.log(data);
          const game = store.state.pk.gameObject;
          const [snake0, snake1] = game.snakes;

          if (data.loser === "all" || data.loser === "A") {
            snake0.status = "die";
          }
          if (data.loser === "all" || data.loser === "B") {
            snake1.status = "die";
          }

          store.commit("updateLoser", data.loser);
        }
      };

      socket.onclose = () => {
        console.log("disconnected!");
      };
    });

    onUnmounted(() => {
      // 给后端发送消息，停止匹配，把当前用户移除匹配池
      store.state.pk.socket.send(
        JSON.stringify({
          event: "stop-matching",
        })
      );
      store.commit("updateStatus", "model");
      store.commit("updateLoser", "none");

      // 关闭socket连接
      socket.close();
    });
  },
};
</script>

<style scoped></style>
